package com.dehui.traders.widgets;

import android.content.Context;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import java.util.LinkedList;
import java.util.List;

public class MyRefrshLayout extends SwipeRefreshLayout{

    private List<ChartLayout> snps = new LinkedList<ChartLayout>();

    public MyRefrshLayout(@NonNull Context context) {
        super(context);
    }

    public MyRefrshLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        ChartLayout snp = getTouchSnp(snps, ev);
        if (snp != null) {
            return false;
        }
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (changed) {
            getAlLViewPager(snps, this);
        }
    }



    /*** 返回我们touch的ViewPager
     *
     * @param mViewPagers
     * @param ev
     * @return
     */
    private ChartLayout getTouchSnp(List<ChartLayout> mViewPagers,
                                    MotionEvent ev) {
        if (mViewPagers == null || mViewPagers.size() == 0) {
            return null;
        }
        Rect mRect = new Rect();
        for (ChartLayout v : mViewPagers) {
            v.getHitRect(mRect); //获取View 被点击 产生响应的对应 Rect 矩形区域。

            if (mRect.contains((int) ev.getX(), (int) ev.getY())) {
                return v;
            }
        }
        return null;
    }

    /**
     * 获取SwipeBackLayout里面的ViewPager的集合
     *
     * @param mViewPagers
     * @param parent
     */
    private void getAlLViewPager(List<ChartLayout> mViewPagers, ViewGroup parent) {
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);
            if (child instanceof ChartLayout) {
                mViewPagers.add((ChartLayout) child);
            } else if (child instanceof ViewGroup) {

                if (child instanceof ChartLayout){
                    mViewPagers.add((ChartLayout) child);
                }
                getAlLViewPager(mViewPagers, (ViewGroup) child);
            }
        }
    }

    public void refresh(){
        getAlLViewPager(snps, this);
    }


}
